import { useState, useEffect, useCallback } from 'react'
import {
  Form,
  Input,
  Modal
} from 'antd'
import { customerUpdate, customerAdd } from '@/api/customer'
import Toast from '@/utils/Toast'
import { cloneDeep, isEmpty } from 'lodash'
import { useTranslation } from 'react-i18next'

const Index = ({ show = false, items, onCancel, onOk }) => {
  const { t } = useTranslation()
  const isAdd = isEmpty(items)
  const [currentShow, setCurrentShow] = useState(false)
  const [form] = Form.useForm()

  const getInitialValues = useCallback(() => {
    if (isEmpty(items)) { 
      form.setFieldsValue(null)
      return
     }
    form.setFieldsValue({ ...items })
  }, [items, form])

  useEffect(() => {
    setCurrentShow(show)
    if (show) getInitialValues()
  }, [show, getInitialValues])

  const handleClose = () => {
    onCancel?.()
    form.resetFields()
  }
  const handleOk = async () => {
    const data = await form.validateFields()
    const currentData = cloneDeep(data)
    const params = { ...currentData }
    const fn = isAdd ? customerAdd : customerUpdate
    if (!isAdd) params.customerId = items.customerId
    await fn(params)
    Toast.success(isAdd ? t('addSuccess') : t('updateSuccess'))
    handleClose?.()
    onOk?.()
  }
  // 添加车类型
  return <Modal onCancel={handleClose} onOk={handleOk} cancelText={t('cancel')} okText={t('save')}centered className='web-modal' title={t('customer.addOrUpdate')} open={currentShow} width='660px'>
    <Form
      form={form}
      className='web-modal-form'
      labelCol={{span: 6}}
      wrapperCol={{span: 16}}
      layout="horizontal"
      colon={false}
    >
      {/* <Form.Item name='userId' label="客户ID" rules={[{ required: true, message: '请输入客户ID' }]}>
        <Input placeholder='请输入客户ID'/>
      </Form.Item> */}
      <Form.Item name='companyName' label={t('customer.companyName')} rules={[{ required: true, message: t('customer.companyName') }]}>
        <Input placeholder={t('inputCompanyName')}/>
      </Form.Item>
      <Form.Item name='companyAddress' label={t('customer.companyAddress2')} rules={[{ required: true, message: t('inputcompanyAddress'), validateTrigger: 'onBlur' }]}>
        <Input placeholder={t('inputcompanyAddress')}/>
      </Form.Item>
      <Form.Item name='customerName' label={t('customer.customerName2')} rules={[{ required: true, message: t('inputCustomerName2') }]}>
        <Input placeholder={t('inputCustomerName2')}/>
      </Form.Item>
      <Form.Item name='customerPhone' label={t('customer.customerPhone')} rules={[{ required: true, message: t('inputCustomerPhone') }]}>
        <Input placeholder={t('inputCustomerPhone')}/>
      </Form.Item>
      <Form.Item name='customerEmail' label={t('customer.customerEmail')}>
        <Input placeholder={t('inputCustomerEmail')}/>
      </Form.Item>
    </Form>
</Modal>
}

export default Index
